﻿using sMES_Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using sMES_Base.service;
using System.Data;
using CUS_Product_QCList_Set_Process.Modules;
using System.Xml;
using CUS_Product_QCList_Set_Process.ORM;

namespace CUS_Product_QCList_Set_Process
{
    /// <summary>
    /// 元件[CUS_Product_QCList_Set_Process]
    /// <auth>gracecai</auth><time>2018/12/4 下午 03:40:57</time>
    /// <description></description>
    /// <list>
    ///   <modify>
    ///     <auth></auth><mantis></mantis><time></time>
    ///     <description></description>
    ///   </modify>
    /// </list>
    /// </summary>
    public class CUS_Product_QCList_Set_Process_utility : BaseUtility
    {
        public CUS_Product_QCList_Set_Process_utility(ref BaseService CurrentService) : base(ref CurrentService)
        {

        }

        public void setProductQCList(RequestContent content)
        {
            // 1.判断明细通过
            content.checklist_detail.ForEach(item =>
            {
                if (string.IsNullOrEmpty(item.check_result))
                    item.check_result = "0";
                else if (!item.do_flag)
                    item.check_result = "0";
            });

            // 2.获取点检单号
            string QCListSerial = GetQCListSerial(content.qclistno + DateTime.Now.ToString("yyMMdd"), content.checklist_detail.Where(_ => _.check_result != "0").Count(), content);

            try
            {
                // 3.写入明细表
                foreach (ORM_QCDetail item in content.checklist_detail)
                {
                    String strDetailField = " Insert Into tblCUSWIPPRDQCListDetail (Creator,CreateDate,QCListSerial, QCItem, QCResult, QCType ";
                    String strDetailValue = $" VALUES ('{CurrentService.GetServiceInfo().account}',GetDate(),'{QCListSerial}','{item.check_item}','{item.check_result}','{item.check_type}' ";

                    if (!string.IsNullOrEmpty(item.check_value))
                    {
                        strDetailField += ",InputValue ";
                        strDetailValue += $",'{item.check_value}'";
                    }

                    if (!string.IsNullOrEmpty(item.std_value))
                    {
                        strDetailField += ",StdValue ";
                        strDetailValue += $",'{item.std_value}'";
                    }

                    if (!string.IsNullOrEmpty(item.range_max))
                    {
                        strDetailField += ",MaxiValue ";
                        strDetailValue += $",'{item.range_max}'";
                    }

                    if (!string.IsNullOrEmpty(item.range_min))
                    {
                        strDetailField += ",MiniValue ";
                        strDetailValue += $",'{item.range_min}'";
                    }

                    if (!string.IsNullOrEmpty(item.InputDataCount))
                    {
                        strDetailField += ",InputDataCount ";
                        strDetailValue += $",'{item.InputDataCount}'";
                    }

                    if (!string.IsNullOrEmpty(item.seq))
                    {
                        strDetailField += ",QCOrder ";
                        strDetailValue += $",'{item.seq}'";
                    }

                    CurrentService.GetDao().ExecuteNonQuery(strDetailField + ")" + strDetailValue + ")");
                }
            }
            catch (ServiceException mex)
            {
                // 发生异常则删除
                CurrentService.GetDao().ExecuteImmediately($" DELETE FROM tblCUSWIPPRDQCListLog WHERE QCLISTSERIAL = '{QCListSerial}'");
                throw;
            }
            catch (Exception)
            {
                // 发生异常则删除
                CurrentService.GetDao().ExecuteImmediately($" DELETE FROM tblCUSWIPPRDQCListLog WHERE QCLISTSERIAL = '{QCListSerial}'");
                throw;
            }
        }

        /// <summary>
        /// 获取点检单号
        /// </summary>
        /// <returns>單號(「點檢表編號(QCLISTNO)」+「建立日(CREATEDATE)」 + XXX 流水號)</returns>
        private String GetQCListSerial(string QCListSerial, int ngCount, RequestContent content)
        {
            // 默认是001开始
            string newSerialNo = QCListSerial + "001";

            string strSQL = $@" Select QCListSerial 
                                From tblCUSWIPPRDQCListLog
                                Where QCListSerial like '{QCListSerial}%'
                                Order by QCListSerial desc";
            DataTable dt = CurrentService.GetDao().Query(strSQL);
            if (dt.Rows.Count > 0)
            {
                string strLastSerial = (Convert.ToString(dt.Rows[0]["QCListSerial"]));
                int intLastSrequence = Convert.ToInt16(strLastSerial.Substring(strLastSerial.Length - 3, 3)) + 1;
                newSerialNo = strLastSerial.Substring(0, strLastSerial.Length - 3) + intLastSrequence.ToString("000");
            }

            // 防止被并发取号，先写入表中
            strSQL = $@" INSERT INTO tblCUSWIPPRDQCListLog(
                              Creator,CreateDate,QCLISTSERIAL,
                              EQUIPMENTNO,LOTNO,PRODUCTNO,OPNO,
                              QCLISTNO,QCRESULT,HANDLE_USERNO,HANDLE_TIME) 
                         VALUES ('{CurrentService.GetServiceInfo().account}',GetDate(),'{newSerialNo}',
                                 '{content.eqpNo}','{content.plotNo}','{content.productno}','{content.opNo}',
                                 '{content.qclistno}',{(ngCount > 0 ? "1" : "0")},'{content.handle_user_no}','{content.handle_time}')";
            CurrentService.GetDao().ExecuteImmediately(strSQL);
            return newSerialNo;
        }
    }
}
